<template>
  <div>
    <!-- 上拉加载 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        @load="onLoad"
      >
        <ArticleItem
          v-for="obj in articlesLinst"
          :key="obj.art_id"
          :artObj="obj"
          @click.native="articleItemFn(obj.art_id)"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 引入组件
import ArticleItem from '@/components/ArticleItem'
// 请求文章列表
import { articlesListApi } from '@/api'
export default {
  data () {
    return {
      articlesLinst: [],
      list: [],
      // 控制加载状态
      loading: false, // 上拉加载
      // 当所有数据加载完毕
      finished: false,
      refreshing: false, // 下拉刷新
      nextTime: new Date()
    }
  },

  props: {
    channel_id: Number
  },
  components: {
    ArticleItem
  },
  methods: {
    // 上拉加载
    onLoad () {
      // 发请求 拿到文章列表数据
      // const res = await articlesListApi({ channel_id: this.channel_id, timestamp: this.nextTime })
      // if (res.data?.data?.results?.length === 0) {
      //   this.finished = true
      // }
      // this.articlesLinst = [...this.articlesLinst, ...res.data.data.results]
      // this.loading = false
      // // this.finished = true
      // this.nextTime = res.data.data.pre_timestamp
      this.getArticleListFn()
    },
    // 获取文章列表
    async getArticleListFn () {
      const res = await articlesListApi({
        channel_id: this.channel_id,
        timestamp: this.nextTime
      })
      if (res.data?.data?.results?.length === 0) {
        this.finished = true
      }
      this.articlesLinst = [...this.articlesLinst, ...res.data.data.results]
      this.loading = false
      this.nextTime = res.data.data.pre_timestamp
      this.refreshing = false
    },
    // 下拉刷新
    onRefresh () {
      // 添加定时器,提高刷新效果
      setTimeout(() => {
        // 下拉刷新时候原数组清空
        this.articlesLinst = []
        // 重新发请求的时候 pre_timestamp 更新到最新的时间
        this.nextTime = new Date()
        // 调用获取文章列表方法 重新获得页面数据
        this.getArticleListFn()
      }, 1000)
    },
    // 文章跳转详情页
    articleItemFn (artId) {
      // 路由跳转传参 query传参拼接在url的?后面
      this.$router.push({
        path: '/article_detail',
        query: {
          aid: artId
        }
      })
      // console.log(1111)
    }
  },
  created () {
    // const res = await articlesListApi({ channel_id: this.channel_id })
    // console.log(res)
    // this.articlesLinst = res.data.data.results
    // this.nextTime = res.data.data.pre_timestamp
    // 页面刚打开的时候调用执行
    this.getArticleListFn()
  }
}
</script>

<style>
</style>
